<?php
/**
 * 错误处理类
 *
 * @author fakis738@gmail.com
 * @link http://www.woophp.com/manual/class/error.lib.php
 * @version $id error.lib.php v0.1 2011-12-03$
 */
class Error_lib
{
	/**
	 * 定义所有错误等级
	 * @var array
	 */
	var $levels = array('user');
	
	/**
	 * 是否打开调试模式
	 * @var bool
	 */
	var $debug = TRUE;
	
	/**
	 * 记录错误日志
	 * @var bool
	 */
	var $log = FALSE;
	
	/**
	 * 发送错误信息至指定邮箱
	 * @var bool
	 */
	var $send_email = FALSE;
	
    public function __construct($param=NULL)
    {
    	if(class_exists('WS'))
    	{
    		$this->path 	= WS::CFG('common/var_path');
    	}
    }
    
    /**
     * 显示错误信息
     * @access public
     * @param string $message
     * @param int $status
     */
	public function show($message, $status=500, $template='error_general')
	{
		WS::setHttpStatus($status);
		
		$back = $this->backTrace();
		$error_info = array(
			'message' 	=> $message,
			'template'	=> $template,
			'file' 		=> $back['file'],
			'line'		=> $back['line'],
		);
		
		if(!empty($this->debug))
		{
			$error_info;
		}
	}
	
	public function sendEmail()
	{
		$_mail = WS::LOAD('email.lib');
		$to = 'fakis738@gmail.com';
		$title = 'woophp.com 错误反馈';
		$content = '';
		$_mail->send($to, $title, $content);
	}
	
	/**
     * 显示404错误
     * @access public
     * @param string $message
     * @param int $status
     */
	public function show_404($log=FALSE)
	{
		$heading = '404 Page Not Found';
		$message = 'The page you requested was not found.';
		
		if($log)
		{
			log_message('error', '404 Page Not Found --> '. $_SERVER['REQUEST_URI']);
		}

		echo $this->show($message, 404, 'error_404');
		exit;
	}
	
	/**
	 * 生成回溯（返回提示错误页面的文件路径、行数、方法、对象）
	 * @access public
	 * @param int $num
	 * @return array
	 */
	public function backTrace($num=1)
	{
		if(function_exists('debug_backtrace'))
		{
			$back = debug_backtrace();
			$trace['file'] = isset($back[$num]['file']) ? $back[$num]['file'] : 'Unknow';
			$trace['line'] = isset($back[$num]['line']) ? $back[$num]['line'] : 'Unknow';
			$trace['function'] = isset($back[$num+1]['function']) ? $back[$num+1]['function'] : 'Unknow';
			$trace['class'] = isset($back[$num+1]['class']) ? $back[$num+1]['class'] : 'Unknow';
			return $trace;
		}
		return array('file' => 'Unknow', 'line' => 'Unknow', 'function' => 'Unknow', 'class' => 'Unknow');
	}
}
